/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trick.it.admin.controller;

import com.appspot.trick.it.admin.Constants;
import com.appspot.trick.it.admin.TrickAdmin;
import com.appspot.trick.it.admin.Util;
import com.appspot.trick.it.admin.bind.ParameterProgressVisibleBinding;
import com.appspot.trick.it.admin.model.ParameterMstModel;
import com.appspot.trick.it.admin.task.ParameterMstGetTask;
import com.appspot.trick.it.admin.task.ParameterMstPutTask;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;

/**
 *
 * @author takahara
 */
public class ParameterController extends AnchorPane implements Initializable {
    
    private final String INITIAL_TEXT_FIRST = "<!DOCTYPE html>"
            + "<html lang=\"ja\">"
            + "<head>"
            + "</head>"
            + "<body id=\"contents\" contenteditable=\"true\" style=\"overflow-x: hidden;\" onKeyDown=\"if((event.metaKey == true) && (event.keyCode==86)){return false;}\">";
    private final String INITIAL_TEXT_LAST = "</body></html>";
    private final String INITIAL_NULL_TEXT = "<p><br></p>";

    @FXML
    private WebView contentsWebView;
    @FXML
    private WebView descriptionWebView;
    @FXML
    public HBox progressIndicatorHBox;
    @FXML
    private Label addKeywordLabel;
    @FXML
    private ListView<String> keywordListView;
    @FXML
    private TextField titleTextField;
    
    private ParameterMstModel parameterMstModel;
    
    private final ParameterMstGetTask parameterMstGetTask = new ParameterMstGetTask();
    private final ParameterMstPutTask parameterMstPutTask = new ParameterMstPutTask();
    
    
    /**
     * コンストラクタ
     */
    public ParameterController() {
        loadFXML();
    }
    
    /**
     * 初期化メソッド
     */
    private void loadFXML() {
        // ---------------------------------------------------
        // FXMLのロードと設定
        // ---------------------------------------------------
        FXMLLoader fxmlLoader = new FXMLLoader(TrickAdmin.class.getResource("fxml/parameter.fxml"));
        fxmlLoader.setRoot(this);
        // 自分自身をコントロールとして設定
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        // プログレスの設定
        progressIndicatorHBox.visibleProperty().bind(
                new ParameterProgressVisibleBinding(
                        parameterMstGetTask,
                        parameterMstPutTask));
        
        // ロードタスクの初期化
        initLoadTask();
        // ロードタスクの実行
        parameterMstGetTask.run();
        
        // 貼付けアクションの初期化
        initPasteAction();
        
        // キーワード追加ラベルの設定
        addKeywordLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                // マウスの左ボタンがクリックされた場合
                if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                    keywordListView.getItems().add("新しいキーワード");
                }
            }
        });
    }
    
    /**
     * 貼付けイベントの初期化
     */
    private void initPasteAction() {
        
        // コンテンツ
        EventHandler contentsWebViewPasteEventHandler = new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if(KeyCombination.keyCombination("Shortcut+V").match(t)) {
                    Clipboard clipboard = Clipboard.getSystemClipboard();
                    String text = null;
                    if (clipboard.hasHtml()) {
                        
                        text = Util.htmlTagRemover(clipboard.getHtml()).replace("\"", "\\\"");
                        
                    }else if(clipboard.hasString()) {
                            text = Util.htmlEscape(clipboard.getString()).replace("\"", "\\\"").replace(Constants.SYSTEM_CRLF, "\\n");
                    }
                    
                    if (text != null) {
                        contentsWebView.getEngine().executeScript("var item = \""
                                + text
                                + "\";"
                                + "document.execCommand('insertHTML', false,item);");
                    }
                }
            }
        };
        contentsWebView.addEventHandler(KeyEvent.KEY_RELEASED, contentsWebViewPasteEventHandler);
        
        // description
        EventHandler descriptionPasteEventHandler = new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if(KeyCombination.keyCombination("Shortcut+V").match(t)) {
                    Clipboard clipboard = Clipboard.getSystemClipboard();
                    String text = null;
                    if (clipboard.hasHtml()) {
                        
                        text = Util.htmlTagRemover(clipboard.getHtml()).replace("\"", "\\\"");
                        
                    }else if(clipboard.hasString()) {
                            text = Util.htmlEscape(clipboard.getString()).replace("\"", "\\\"").replace(Constants.SYSTEM_CRLF, "\\n");
                    }
                    
                    if (text != null) {
                        descriptionWebView.getEngine().executeScript("var item = \""
                                + text
                                + "\";"
                                + "document.execCommand('insertHTML', false,item);");
                    }
                }
            }
        };
        descriptionWebView.addEventHandler(KeyEvent.KEY_RELEASED, descriptionPasteEventHandler);
    }
    
    /**
     * 保存アクション
     * @throws IOException 
     */
    @FXML
    protected void saveAction() throws IOException {
        
        ParameterMstModel mstModel = new ParameterMstModel();
        
        // コンンテンツ
        if (getContentsHtmlText().trim().equals(INITIAL_NULL_TEXT)) {
            mstModel.setTopContent(null);
        }else {
            mstModel.setTopContent(getContentsHtmlText());
        }
        
        // description
        String bodyInnerHTML = (String)descriptionWebView.getEngine().executeScript("document.body.innerHTML");
        String description = Util.HtmlTagRemover(bodyInnerHTML);
        if (description.trim().equals("")) {
            mstModel.setDescription(null);
        }else {
            mstModel.setDescription(description);
        }
        
        // キーワード
        mstModel.setKeyWordList(keywordListView.getItems());
        
        // タイトル
        String title = titleTextField.getText();
        if (title.trim().equals("")) {
            mstModel.setTitle(null);
        }else {
            mstModel.setTitle(title);
        }
        
        // 更新タスクの実行
        parameterMstPutTask.run(mstModel);
    }
    
    /**
     * ロードタスクの初期化
     */
    private void initLoadTask() {
        parameterMstGetTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {

                parameterMstModel = (ParameterMstModel) t.getSource().getValue();

                // コンテンツの設定
                String content = parameterMstModel.getTopContent();
                if (content == null) {
                    contentsWebView.getEngine().loadContent(INITIAL_TEXT_FIRST + INITIAL_NULL_TEXT + INITIAL_TEXT_LAST);
                } else {
                    contentsWebView.getEngine().loadContent(INITIAL_TEXT_FIRST + content + INITIAL_TEXT_LAST);
                }
                
                // description
                String description = parameterMstModel.getDescription();
                if (description == null) {
                    descriptionWebView.getEngine().loadContent(INITIAL_TEXT_FIRST + INITIAL_NULL_TEXT + INITIAL_TEXT_LAST);
                } else {
                    descriptionWebView.getEngine().loadContent(INITIAL_TEXT_FIRST + description + INITIAL_TEXT_LAST);
                }
                
                // キーワードリスト
                if (parameterMstModel.getKeyWordList() != null) {
                    keywordListView.getItems().setAll(parameterMstModel.getKeyWordList());
                }
                
                // タイトル
                if (parameterMstModel.getTitle() != null) {
                    titleTextField.setText(parameterMstModel.getTitle());
                }
            }
        });

    }
    
    /**
     * HTML Text の取得
     * @return 
     */
    private String getContentsHtmlText() {
        
        String bodyInnerHTML = (String)contentsWebView.getEngine().executeScript("document.body.innerHTML");
        
        return bodyInnerHTML.replace("<p></p>", "");
    }

}
